package authen;

import org.apache.shiro.SecurityUtils;
        import org.apache.shiro.authc.IncorrectCredentialsException;
        import org.apache.shiro.authc.UnknownAccountException;
        import org.apache.shiro.authc.UsernamePasswordToken;
        import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
        import org.apache.shiro.mgt.DefaultSecurityManager;
        import org.apache.shiro.subject.Subject;
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import realm.CustomerMd5Realm;

        import java.util.Arrays;

/**
 * 测试Shiro认证器：使用CustomerMd5Realm（md5加密）
 *
 * @author lwh
 */
@SuppressWarnings("ALL")
public class TestCustomerMd5Authenticator {

    private static Logger logger = LoggerFactory.getLogger(TestCustomerRealmAuthenticator.class);

    public static void main(String[] args) {
        // 创建安全管理器
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        // 创建自定义Realm
        CustomerMd5Realm realm = new CustomerMd5Realm();
        // 创建hash凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置匹配器使用md5进行加密
        credentialsMatcher.setHashAlgorithmName("md5");
        // 设置加密散列次数
        credentialsMatcher.setHashIterations(1024);
        // 设置realm中的凭证匹配器
        realm.setCredentialsMatcher(credentialsMatcher);
        // 设置Realm
        securityManager.setRealm(realm);
        // 使用安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        // 获取主体
        Subject subject = SecurityUtils.getSubject();
        // 创建token
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
        // 登录认证
        try {
            subject.login(token);
            logger.info("认证状态：" + subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            logger.info("用户信息错误");
        } catch (IncorrectCredentialsException e) {
            logger.info("凭证信息错误");
        }

        // 授权
        if (subject.isAuthenticated()) {
            logger.info(String.valueOf(subject.hasRole("admin")));
            logger.info(String.valueOf(subject.hasAllRoles(Arrays.asList("admin", "user"))));
            logger.info(Arrays.toString(subject.hasRoles(Arrays.asList("admin", "super"))));

            logger.info(String.valueOf(subject.isPermitted("user:update:01")));
            logger.info(String.valueOf(subject.isPermitted("product:update")));

            logger.info(Arrays.toString(subject.isPermitted("user:*:01", "product:create:*")));
        }

    }


}
